import { useState, useEffect } from "react";
import { jwtDecode } from "jwt-decode";

export const useAuth = () => {
  const [isAuthenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    window.addEventListener("storage", checkTokenValid);
    return () => {
      window.removeEventListener("storage", checkTokenValid);
    };
  }, []);

  const checkTokenValid = () => {
    const token = localStorage.getItem("token");
    if (token) {
      try {
        const decodeToken = jwtDecode(token);
        const currentTime = Date.now() / 1000; // 转为秒
        return setAuthenticated(decodeToken.exp! > currentTime);
      } catch (error) {
        console.log("token 解析失败", error);
      }
    }
    setAuthenticated(false);
  };

  return {
    isAuthenticated,
  };
};
